package com.yunduo.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.Address;
import com.yunduo.entity.User;
import com.yunduo.service.AddressService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户地址管理
 */
@RestController
@RequestMapping("/faddress")
public class UserAddressController {

    @Resource
    private AddressService addressService;

    //拉取用户的所有地址
    @GetMapping("/get")
    public CommonReturn getAllAddress(){
        //本地缓存获取用户
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        List<Address> list = addressService.list(new LambdaQueryWrapper<Address>().eq(Address::getUserId, user.getId()));
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("list",list);
    }

    //拉取某个地址
    @GetMapping("/get/{addressId}")
    public CommonReturn getAddress(@PathVariable("addressId") String addressId){
        Address address = addressService.getById(addressId);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS).setData("address",address);
    }

    //添加地址
    @PostMapping("/add")
    public CommonReturn addAddress(@RequestBody Address address){
        //本地缓存获取用户
        User user = JwtUtils.getDataByJwtToken(YunDuoUtils.getRequest());
        if(user == null){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        address.setId(null);
        address.setUserId(user.getId());
        addressService.addAddress(address);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //修改地址
    @PostMapping("/update")
    public CommonReturn updateAddress(@RequestBody Address address){
        if(StringUtils.isEmpty(address)){
            return CommonReturn.ERROR(ResultCode.ERROR);
        }
        addressService.updateAddress(address);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

    //删除地址
    @DeleteMapping("/delete/{addressid}")
    public CommonReturn deleteAddress(@PathVariable("addressid") String id){
        addressService.removeById(id);
        return CommonReturn.SUCCESS(ResultCode.SUCCESS);
    }

}
